#!/bin/sh

####### quality.sh #########
# Submit quality job
############################
source ./sefunctions.sh

chmod a+x *.sh
chmod a+x *.pl

workflow=$1
lfndir="/biomed/user/d/dttung/panam/outputs/$workflow"

# Verify if there is the file quality.tar.gz under $lfndir
# If YES, that means other 'quality' jobs has done and has results
qualityverify=`./pnls.sh outputs $workflow | grep "quality"`
if [ -n "$qualityverify" ]; then # File has been uploaded
	echo "File qualitytool.tar.gz has been uploaded by other 'quality' job"
	exit 0;
fi
# Untar/zip $workflow.tar.gz (this is input files)
echo -ne "Check $workflow.tar.gz ..."
if [ ! -f $workflow.tar.gz ]; then
	echo "File $workflow.tar.gz is not existed"
	exit 1;
fi
echo " done!"
tar -xzf $workflow.tar.gz
# $workflow.tar.gz extract to 'test' directory, not '$workflow' directory

echo -ne "Check qualitytool.tar.gz ..."
# Untar/zip qualitytool.tar.gz (this is tool files)
if [ ! -f qualitytool.tar.gz ]; then
	echo "File qualitytool.tar.gz is not existed"
	exit 1;
fi
echo " done!"
tar -xzf qualitytool.tar.gz

# Extract qualitytool.tar.gz => 'bin' directory
cd bin
chmod a+x compileemboss.sh # This is the file to compile Emboss
./compileemboss.sh > ../compileemboss.log
cd ..

# quality_v3_grid.pl and panam.ini are submitted in InputSandbox, no need to be checked
echo "Run quality"
chmod a+x quality.pl
./quality.pl panam.ini

# Pack the results
tar -czf quality.tar.gz results test/barcode.txt # barcode will be needed for preprocess as well
echo -ne "Check results ... "
samplesize=`ls -l results/ | grep sample_all | cut -d" " -f5`
# debug
echo "|$samplesize|"
if [ $samplesize -lt 100 ]; then
	echo ""
	echo "Error: running quality has no results"
	exit 1;
fi
echo "done! sample_all size is $samplesize"
# Copy the results to the grid
# Check again before upload
qualityverify=`./pnls.sh outputs $workflow | grep "quality"`
if [ -n "$qualityverify" ]; then # File has been uploaded
	echo "File qualitytool.tar.gz has been uploaded by other 'quality' job"
	exit 0;
fi

echo -ne "Copy the results to the grid ..."

CopyToGrid $lfndir quality.tar.gz 0 copyquality.log # No replica at the moment
echo "Done!"
echo "========================"
echo "quality finished successfully"